package org.etom.impl.ui.wizards;

import java.util.List;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.etom.connector.datatypes.IMoodleModule;
import org.etom.impl.ui.Activator;
import org.etom.impl.ui.common.IconConstants;
import org.etom.impl.ui.jobs.UploadJob;
import org.etom.impl.ui.preference.PreferenceManager;
import org.etom.impl.ui.util.Logger;

public class UploadWizard extends Wizard {

  private IStructuredSelection selection;
  private UploadWizardPage uploadPage;
  private UploadWizardPage1 uploadPage1;
  
  public UploadWizard(IStructuredSelection selection) {
    this.selection = selection;
    init();
  }
  
  @Override
  public IWizardPage getNextPage(IWizardPage page) {
    if (page == uploadPage) {
      uploadPage1.setFileNameTemplate(
          ((UploadWizardPage) uploadPage).getFileNameTemplate());
      return uploadPage1;
    }
    return super.getNextPage(page);
  }

  @Override
  public void addPages() {
    if (uploadPage == null) {
      uploadPage = new UploadWizardPage(selection,
          PreferenceManager.getUploadFileNameTemplate());
    }
    addPage(uploadPage);
    
    if (uploadPage1 == null) {
      uploadPage1 = new UploadWizardPage1();
    }
    addPage(uploadPage1);
  }

  @Override
  public boolean performFinish() {
    try {
      IMoodleModule selectedModule = uploadPage1.getSelectedModule();
      if (null == selectedModule) return false;
      String fileName = uploadPage1.getFileName();
      if (fileName == null) return false;
      fileName = fileName.trim();
      if (fileName.length() == 0) return false;
      List<?> selectedResources = uploadPage.performFinish(fileName);
      UploadJob uploadJob = new UploadJob(selectedResources, fileName, selectedModule);
      uploadJob.setUser(true);
      uploadJob.schedule();
      return true;
    } catch (Exception e) {
      Logger.ERROR(WizardsMessages.Upload_Wizard_Set_Content_Fail, e);
      return false;
    }
  }

  private void init() {
    setDefaultPageImageDescriptor(
        ImageDescriptor.createFromFile(Activator.class,
            IconConstants.WIZARD_UPLOAD_ICON_PATH));
    setWindowTitle(WizardsMessages.Upload_Wizard_Title);
  }
  
}
